package com.jxb.demo.es;

import com.jxb.demo.es.entity.OrderEntity;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class SearchService {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public void addEntity(OrderEntity orderEntity){
        elasticsearchRestTemplate.save(orderEntity);
    }

    public List<OrderEntity> findEntity(String fieldName,Object text){
        //elasticsearchRestTemplate
        List<OrderEntity> entityList = new ArrayList<>();
        QueryBuilder matchQuery = QueryBuilders.matchQuery(fieldName,text);
         //QueryBuilders.termQuery(fieldName,text);
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery).build();
        SearchHits<OrderEntity> hits = elasticsearchRestTemplate.search(searchQuery,OrderEntity.class);
        hits.get().forEach(hit->{
            entityList.add(hit.getContent());
        });
        QueryBuilders.rangeQuery("abc");
        return entityList;
    }

}
